package com.example.gb28181.request.impl;

import com.example.gb28181.entity.MessageNotifyEntity;
import com.example.gb28181.enums.MessageEnum;
import com.example.gb28181.enums.SipMethodEnum;
import com.example.gb28181.request.SIPRequestProcessor;
import com.example.gb28181.service.SIPProcessorObserver;
import com.example.gb28181.strategy.MessageStrategy;
import com.example.gb28181.utils.XstreamUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.sip.RequestEvent;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/21
 */
@Component
@AllArgsConstructor
@Service
public class MessageRequestProcessor implements InitializingBean, SIPRequestProcessor {
    private final SIPProcessorObserver sipProcessorObserver;
    private final static SipMethodEnum MESSAGE = SipMethodEnum.MESSAGE;

    private final List<MessageStrategy> messageStrategyList;


    @Override
    public void process(RequestEvent event) throws UnsupportedEncodingException {
        byte[] rawContent = event.getRequest().getRawContent();
        MessageNotifyEntity messageNotifyEntity = XstreamUtil.toBean(MessageNotifyEntity.class, rawContent);
        for (MessageStrategy messageStrategy:messageStrategyList
             ) {
            if (messageStrategy.support(MessageEnum.getMethodEnumByName(messageNotifyEntity.getCmdType()))){
                messageStrategy.processor();
            }
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 添加消息处理的订阅
        sipProcessorObserver.addRequestProcessor(MESSAGE, this);
    }
}
